package com.myrice.jms.impl;

import java.nio.ByteBuffer;

import com.myrice.core.impl.DefaultContext;
import com.myrice.jms.MessageFactory;
import com.myrice.jms.MsgRequest;
import com.myrice.jms.MsgResponse;
import com.myrice.util.ByteBufferUtils;

public class DefaultMessage extends DefaultContext implements MsgRequest,
		MsgResponse {

	private DefaultMsgSession session;
	private int mode;
	private ByteBuffer data;
	private boolean response;

	private short status;

	@Override
	public String toString() {
		return new StringBuilder("<").append("data:").append(data)
				.append("  response: ").append(response).append("  mode:")
				.append(mode).append(">").toString();
	}

	public void init(DefaultMsgSession session, ByteBuffer packet) {
		this.status = STATUS_SUCCESS;
		this.session = session;
		this.read(packet);

	}

	public void read(ByteBuffer packet) {
		response = packet.get() == DefaultMsgSession.HEAD_RESPONSE;// 是否为响应消息
		mode = packet.getInt();// 编号
		data = packet;
	}

	public void setSession(DefaultMsgSession session) {
		this.session = session;
	}

	public DefaultMsgSession getSession() {
		return session;
	}

	public String getRemoteAddress() {
		return session.getRemoteAddress();
	}

	public int getRemotePort() {
		return session.getRemotePort();
	}

	public ByteBuffer getData() {
		return data;
	}

	public boolean isResponse() {
		return response;
	}

	public int length() {
		return data != null ? data.remaining() : 0;
	}

	public boolean isValid() {
		return mode != 0;
	}

	public int getMode() {
		return mode;
	}

	public void setStatus(short status) {
		this.status = status;
	}

	public void setData(ByteBuffer msg) {
		this.data = msg;
	}

	/**
	 * 发送响应消息
	 */
	public void flush() {
		if (mode == 0)
			return;

		boolean has = data != null;

		if (has && data.capacity() - data.limit() >= 2) {
			ByteBufferUtils.offset(data, 2);
			data.limit(data.limit() + 2);
			data.putShort(0, status);
		} else {
			ByteBuffer resp = ByteBuffer.allocate(2 + (has ? data.remaining()
					: 0));
			resp.putShort(status);// 响应状态
			if (has) {
				resp.put(data);// 响应数据
			}
			resp.flip();
			data = resp;
		}

		session.send(DefaultMsgSession.HEAD_RESPONSE, mode, data);

		data = null;
		mode = 0;
	}

	public void destory() {
		MessageFactory f = null;
		if (session != null)
			f = session.getServerHandler().getMessageFactory();

		this.mode = 0;
		this.response = false;
		this.status = 0;
		this.session = null;
		this.data = null;
		this.clear();

		if (f != null)
			f.recycle(this);
	}

	protected DefaultMessage() {
	}

}
